<?php

namespace App\Http\Controllers\api\user;

use App\Common\statement\CommonStatement;
use App\Common\statement\Fillable;
use App\Http\Controllers\api\base\BaseController;
use App\Http\Controllers\api\pay\PayTrait;
use App\Http\Requests\auth\AuthRequest;
use App\Http\Requests\base\IdRequest;
use App\Http\Requests\user\BillRequest;
use App\Http\Requests\user\EditRequest;
use App\Http\Requests\user\FeedbackRequest;
use App\Http\Resources\base\PageResource;
use App\Http\Resources\funds\RechargeCollection;
use App\Http\Resources\user\RebatePageCollection;
use App\Http\Resources\user\CouponPageCollection;
use App\Http\Resources\user\IntegralResource;
use App\Http\Resources\user\SuperiorPageCollection;
use App\Http\Resources\user\UserResource;
use App\Jobs\user\BuildUserSuperior;
use App\Models\config\Config;
use App\Models\fund\Cash;
use App\Models\fund\Coupon;
use App\Models\fund\Rebate;
use App\Models\fund\RechargeConfig;
use App\Models\fund\Voucher;
use App\Models\User;
use App\Models\user\Depart;
use App\Models\user\Feedback;
use App\Models\user\MoneyDetail;
use App\Models\user\SportLog;
use App\Models\user\ThirdLogin;
use App\Models\user\UserSuperior;
use App\Services\common\SmsService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;


class UserController extends BaseController
{
    /**
     * 获取用户信息
     */
    public function getInfo(Request $request)
    {

        if ($request->id && $request->id != $this->user_id){
            $user = User::findOrFail($request->id);
            $user->money = "0";
            $user->phone = hidePhone($user->phone);
        }else{
            $user = $this->user;
        }
        if($user->branch_id){
            $user['branch'] = Depart::where('id',$user->branch_id)->value('name');
        }
        if($user['depart_id']){
            $depart = explode(',',$user->depart_id);
            $user['office'] = '';
            if(count($depart) > 1){
                $user['leader'] = $user->name;
                foreach ($depart as $value){
                    $office[] = Depart::where('id',$value)->value('name');
                }
                $user['office'] = implode(',',$office);
            }else{
                $user['office'] = Depart::where('id',$user->depart_id)->value('name');
                $user['leader'] = User::where('depart_id',$user['depart_id'])->value('name');
            }
            $user['organization'] = CommonStatement::organization_type[$depart['type']];
        }

        return success($user);
    }

    /**
     * 组织
     * @param Request $request
     * @return mixed
     */
    public function organization(Request $request)
    {
        $type = $request->type;
        $data = Depart::where('type',$type)->where('pid','!=',0)->select(['name','id','leader_id'])->get()->toArray();
        $data = array_column($data,null,'id');
        foreach ($data as $key => $val){
            $data[$key]['member'] = [];
        }
        $depart_id_arr = array_column($data,'id');
        if($type == 1){
            $user = User::whereIn('depart_id',$depart_id_arr)
                ->orderByDesc('level')
                ->select(['id as user_id','header_img','name','duty','phone','depart_id','level','branch_id'])
                ->get()->toArray();
            foreach ($data as $value){
                if($value['leader_id']){
                    $data[$value['id']]['member'][] = User::where('id',$value['leader_id'])
                        ->select(['id as user_id','header_img','name','duty','phone','depart_id','level','branch_id'])
                        ->first();
                }
            }
            foreach ($user as $item){
                $data[$item['depart_id']]['member'][] = $item;
            }
        }else{
            $user = User::whereIn('branch_id',$depart_id_arr)
                ->orderByDesc('level')
                ->select(['id as user_id','header_img','name','duty','phone','depart_id','level','branch_id'])
                ->get()->toArray();
            foreach ($user as $item){
                $data[$item['branch_id']]['member'][] = $item;
            }
        }
        return success(array_values($data));
    }

    /**
     * 余额明细
     * @return mixed
     */
    public function money_detail(Request $request)
    {
        $pageSize = $request->pageSize??15;
        $rows = MoneyDetail::where('user_id',$this->user_id)->paginate($pageSize);
        return success(new PageResource($rows));
    }

    /**
     * 积分榜
     * @return mixed
     */
    public function scoreRank()
    {
        $data = User::orderByDesc('money')->select(['id as user_id','name','header_img','duty','money as score'])->get();
        return success($data);
    }
    
    /**
     * 修改用户信息
     */
    public function edit(EditRequest $request)
    {
        $params = $request->only(['nickname','header_img','phone','sex']);

        if ($params['phone']){
            $have = User::where('phone',$params['phone'])->where('id','!=',$this->user_id)->first();
            if ($have){
                return error("手机号码已绑定其它账号!");
            }
        }

        if (empty($params) ){
            return error('参数不能为空!');
        }

        try{
            DB::beginTransaction();

            if ($params){
                foreach ($params as $k => $v){
                    $this->user->$k = $v;
                }
                $this->user->save();
            }

            DB::commit();
        }catch (\Exception $e){
            DB::rollback();
            return error($e->getMessage());
        }
        return successWithMsg('修改成功');

    }

    /**
     * 用户反馈
     */
    public function feedback(FeedbackRequest $request)
    {
        $map = $request->only(['content']);
        $map['user_id'] = $this->user_id;

        $result = Feedback::create($map);
        if ($result){
            return successWithMsg("反馈提交成功");
        }

        return error();
    }



    /**
     * 获取上层信息
     */
    public function superiorInfo()
    {
//        if (!$this->user->superior_id){
//            return error(CommonStatement::superiorInfo);
//        }
        $arr = Config::getConfig("wx_code,wx_id");

        if ($this->user->level != 5){
            $superior = UserSuperior::whereUserId($this->user_id)->whereBetween('user_level',[4,5])->orderBy('user_level')->first();
            if ($superior){
                $arr['wx_code'] = $superior->superior->wx_code;
                $arr['wx_id'] = $superior->superior->wx_id;
            }
        }

        return success($arr);
    }

    public function info()
    {
        $arr = Config::getConfig("wx_code,wx_id");
        return success($arr);
    }

    /**
     * 我的钱包
     */
    public function wallet()
    {
        $map['user_id'] = $this->user_id;
        $map['status']  = 1;
        $data['cash'] = Cash::where($map)->sum('money')??0;
        $map2['user_id'] = $this->user_id;
        $map2['money_type'] = 1;
        $map2['status'] = 0;
        $data['rebate'] = Rebate::where($map2)->sum('amount')??0;
        $data['money'] = $this->user->money??0;
        return success($data);

    }
}